﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QD.Entity;
using QD.Data.Parameter;
using QD.Data.Page;
using System.Data;

namespace QD.Repository
{
    public abstract class RepositoryMySql<T> : RepositorySql<T> where T : DbEntity, IDbEntity<T>, new()
    {

        public RepositoryMySql()
        {
            ParamBuilder = new MySqlParamBuilder();
            DBHelper = QD.DataBase.DBHelper.MYSQLHelper.Instance;
            this.QuoteLeft = '`';
            this.QuoteRight = '`';
            this.ParamPrev = "?p_";
        }


        protected override void Init()
        {
            base.Init();
            PageListSQL = "uSP_Find_PageList";
            if (dtContext.PrimaryKey.AutoInCrement)
                InsertCommand += "SET " + ParamPrev + dtContext.PrimaryKey.Name + "=last_insert_id();";
        }

        public override PageList<U> Find<U>(int page, int pagesize, string where, string order)
        {

            IList<U> list = null;
            int total = 0;
            IDbDataParameter[] parameters = {
                         ParamBuilder.Create("?p_TableName",dtContext.Name),
                         ParamBuilder.Create("?p_Fields","*"),
                         ParamBuilder.Create("?p_Page",page>0?page:1),
                         ParamBuilder.Create("?p_PageSize",pagesize),
                         ParamBuilder.Create("?p_Where",where),
                         ParamBuilder.Create("?p_Order",order),
                         ParamBuilder.Create("?p_RowCount",0, ParameterDirection.Output),
                     };

            list = FindEntitys<U>(ConnectionString, CommandType.StoredProcedure, PageListSQL, parameters);

            total = Convert.ToInt32(parameters[6].Value);

            PageList<U> records = new PageList<U>(list, total);

            return records;
        }

    }
}
